/*
 * @Author: dengzewei
 * @Date: 2025-04-15 13:08:39
 * @LastEditors: dengzewei
 * @LastEditTime: 2025-04-15 18:19:56
 * @FilePath: /chrome_new/webpack.config.js
 * @Description: 
 * 
 * Copyright (c) 2025 by 抖查查, All Rights Reserved. 
 */
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const JavaScriptObfuscator = require('webpack-obfuscator');

module.exports = (env, argv) => {
  const isDevelopment = argv.mode === 'development';

  // 确保在生产模式下 entry 始终有值
  const entry = {
    background: './background.js', // 这里确保有入口文件
    ...(isDevelopment && {
      popup: './popup.js', // 仅在开发模式下添加 popup 作为入口
    })
  };

  const config = {
    entry, // 在此定义 entry，确保它总是有效
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: '[name].js',
    },
    optimization: {
      minimize: !isDevelopment, // 生产模式时进行压缩
    },
    devtool: isDevelopment ? 'source-map' : false, // 开发模式启用 source-map
    plugins: [
      new CopyPlugin({
        patterns: [
          { from: 'manifest.json', to: 'manifest.json' },
          { from: 'popup.html', to: 'popup.html' },
          { from: 'popup.js', to: 'popup.js' },
          { from: 'styles.css', to: 'styles.css' },
          { from: 'images', to: 'images' },
          { from: 'js', to: 'js' },
          { from: 'douyin', to: 'douyin' },
          { from: 'aidso', to: 'aidso' },
          { from: 'background.js', to: 'background.js' }, // 确保 background.js 会被复制到 dist 文件夹
        ],
      })
    ],
    mode: argv.mode, // 使用命令行传入的 mode（development 或 production）
  };

  // 只在生产环境下添加混淆插件
  if (!isDevelopment) {
    config.plugins.push(
      new JavaScriptObfuscator({
        rotateStringArray: true,
        stringArray: true,
        stringArrayEncoding: ['base64'],
        stringArrayThreshold: 0.75,
        compact: true,
        controlFlowFlattening: true,
        controlFlowFlatteningThreshold: 0.75,
        deadCodeInjection: true,
        deadCodeInjectionThreshold: 0.4,
        debugProtection: true,
        debugProtectionInterval: true,
        disableConsoleOutput: true,
        identifierNamesGenerator: 'hexadecimal',
        log: false,
        numbersToExpressions: true,
        renameGlobals: false,
        selfDefending: true,
        simplify: true,
        splitStrings: true,
        splitStringsChunkLength: 10,
        stringArrayWrappersCount: 2,
        stringArrayWrappersChainedCalls: true,
        stringArrayWrappersParametersMaxCount: 4,
        stringArrayWrappersType: 'function',
        stringArrayThreshold: 0.75,
        transformObjectKeys: true,
        unicodeEscapeSequence: false
      }, ['background.js'])
    );
  }

  return config;
};
